package com.gupao.p7store.common.utils.file;

import cn.hutool.core.io.FileUtil;
import com.gupao.p7store.common.utils.io.IoTools;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * 文件处理工具类
 *
 * @author Lion Li
 */
@Slf4j
public class FileUtils extends FileUtil {

    /**
     * 下载文件名重新编码
     *
     * @param response     响应对象
     * @param realFileName 真实文件名
     * @return
     */
    public static void setAttachmentResponseHeader(HttpServletResponse response, String realFileName) throws UnsupportedEncodingException {
        String percentEncodedFileName = percentEncode(realFileName);

        StringBuilder contentDispositionValue = new StringBuilder();
        contentDispositionValue.append("attachment; filename=")
            .append(percentEncodedFileName)
            .append(";")
            .append("filename*=")
            .append("utf-8''")
            .append(percentEncodedFileName);

        response.addHeader("Access-Control-Allow-Origin", "*");
        response.addHeader("Access-Control-Expose-Headers", "Content-Disposition,download-filename");
        response.setHeader("Content-disposition", contentDispositionValue.toString());
        response.setHeader("download-filename", percentEncodedFileName);
    }

    /**
     * 百分号编码工具方法
     *
     * @param s 需要百分号编码的字符串
     * @return 百分号编码后的字符串
     */
    public static String percentEncode(String s) throws UnsupportedEncodingException {
        String encode = URLEncoder.encode(s, StandardCharsets.UTF_8.toString());
        return encode.replaceAll("\\+", "%20");
    }

    public static File createFolder(StringBuffer layer1) {
        File folder = new File(layer1.toString());
        if (!folder.exists()) {
            folder.mkdirs();
        }
        return folder;
    }

    public static File createFolder(String folderPath) {
        File folder = new File(folderPath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        return folder;
    }

    public static File createFile(String filePath) {
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                log.error("文件io异常");
            }
        }
        return file;
    }

    public static File createFile(StringBuffer layer) {
        File file = new File(layer.toString());
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                log.error("文件io异常");
            }
        }
        return file;
    }

    public static void writeDataToFile(File file, String content) {
        FileWriter fw = null;
        try {
            fw = new FileWriter(file);
            fw.write(content);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoTools.close(fw);
        }
    }

    public static void commonCreateFile(StringBuffer layer5, String todo) {
        log.info(layer5.toString());
        File file5 = createFile(layer5);
        writeDataToFile(file5, todo);
    }

    /**
     * 下载文件
     *
     * @param downloadUrl 下载地址
     * @param filePath    下载文件保存路径
     */
    public static void download(String downloadUrl, String filePath) {
        BufferedInputStream in = null;
        BufferedOutputStream out = null;
        try {
            //获取输入流
            URL url1 = new URL(downloadUrl);
            URLConnection urlConnection = url1.openConnection();
            urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/92.0.4515.159 Safari/537.36");
            in = new BufferedInputStream(url1.openStream());
            //创建文件流
            File file = new File(filePath);
            out = new BufferedOutputStream(new FileOutputStream(file));
            //缓冲字节数组
            byte[] data = new byte[1024];
            int len = 0;
            while ((len = in.read(data)) != -1) {
                out.write(data, 0, len);
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IoTools.close(out,in);
        }
    }
}
